package models

import (
	"chinasoccer/pkg/utils"
	"fmt"
	"log"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Worker struct {
	gorm.Model
	WorkerID       string `json:"workerid" form:"workerid" gorm:"type:varchar(20);not null;unique;" binding:"required"`
	WorkerName     string `json:"workername" form:"workername" gorm:"type:varchar(20);not null;" binding:"required"`
	WorkerPassword string `json:"workerpassword" form:"workerpassword" gorm:"type:varchar(20);not null;" binding:"required"`
	WorkerLevel    string `json:"workerlevel" form:"workerlevel" gorm:"type:varchar(20);not null;" binding:"required"`
	WorkerPhone    string `json:"workerphone" form:"workphone" gorm:"type: varchar(20);not null;unique" binding:"required"`
	WorkerSalary   int    `json:"workersalary" form:"workersalary" gorm:"type: serial;not null;" binding:"required"`
	WorkerOthers   string `json:"workerothers" form:"workerothers" gorm:"type:varchar(20);"`
	IsDel          bool   `json:"isdel" form:"isdel" gorm:"type:boolean default false;"`
}

func getJson(c *gin.Context) (Worker, error) {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)
	workerid := json["workerid"]
	workername := json["workername"]
	workerpassword := json["workerpassword"]
	workerlevel := json["workerlevel"]
	workphone := json["workerphone"]
	workerothers := json["workerothers"]
	workersalary, err := strconv.Atoi(json["workersalary"])
	worker := Worker{
		WorkerID:       workerid,
		WorkerName:     workername,
		WorkerPassword: workerpassword,
		WorkerPhone:    workphone,
		WorkerLevel:    workerlevel,
		WorkerSalary:   workersalary,
		WorkerOthers:   workerothers,
	}
	if err != nil {
		return Worker{}, err
	}
	return worker, err
}

// 获取所有的 Workers
func GetAllWorkers(workerParam map[string]interface{}) ([]Worker, int64, error) {
	var workerdata []Worker
	pagenum := workerParam["pagenum"].(int)
	pagesize := workerParam["pagesize"].(int)
	query := workerParam["query"].(string)
	if query == "" {
		var total int64
		err := db.Table("workers").Where("is_del = false").Count(&total).Error
		if err != nil {
			return workerdata, 0, err
		}
		err = db.Table("workers").Where("is_del = false").Offset((pagenum - 1) * pagesize).Limit(pagesize).Find(&workerdata).Error
		fmt.Println("total = ", total)
		return workerdata, total, err
	}
	workerName := query

	var worker Worker
	err := db.Table("workers").Where("worker_id = ?", workerName).First(&worker).Error
	workerdata = append(workerdata, worker)
	if err != nil {
		return workerdata, 0, err
	}

	return workerdata, 1, err
}

// 增加员工的信息
func AddWorker(c *gin.Context) (Worker, int64, error) {
	worker, err := getJson(c)
	if err != nil {
		return Worker{}, 0, err
	}
	var total int64
	db.Table("workers").Where("worker_id = ? or worker_phone = ?", worker.WorkerID, worker.WorkerPhone).Count(&total)
	fmt.Println(total)
	if total == 0 {
		db.Table("workers").Create(&worker)
		return worker, 0, err
	}
	return worker, total, err
}

// 修改员工信息
func UpdateWorker(c *gin.Context) (Worker, error) {
	worker, err := getJson(c)
	if err != nil {
		return Worker{}, err
	}
	err = db.Table("workers").Where("worker_id = ?", worker.WorkerID).Updates(&worker).Error
	return worker, err
}

// 删除员工
func DelWorker(c *gin.Context) error {
	id := c.Params.ByName("id")
	err := db.Table("workers").Where("worker_id = ?", id).Update("is_del", true).Error
	if err != nil {
		return err
	}
	err = db.Table("workers").Where("worker_id = ?", id).Update("worker_phone", utils.RandomString(19)).Error
	if err != nil {
		return err
	}
	err = db.Table("workers").Where("worker_id = ?", id).Update("worker_id", utils.RandomString(19)).Error
	if err != nil {
		return err
	}
	return err
}

func GetUser(c *gin.Context) (Worker, error) {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)
	username := json["username"]
	password := json["password"]
	ok, err := cacher.Exists(username)
	if err != nil {
		log.Fatalf("redis error, err:%v", err)
	}
	if ok {
		pwd, err := cacher.GetString(username)
		if pwd == password {
			return Worker{
				WorkerID:       username,
				WorkerPassword: password,
			}, err
		}
	} else {
		var worker Worker
		err := db.Table("workers").Where("worker_id = ? AND worker_password = ?", username, password).First(&worker).Error
		if err == nil {
			// 在 redis 中设置该 用户名和密码 下次直接从 redis 中找
			cacher.Do("Set", worker.WorkerID, worker.WorkerPassword)
		}
		return worker, err
	}
	return Worker{}, nil
}

func GetDoc(c *gin.Context) (Worker, error) {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)
	workerID := json["workerid"]
	var worker Worker
	err := db.Table("workers").Where("worker_id = ?", workerID).First(&worker).Error
	fmt.Println(worker)
	return worker, err
}
